#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
//链表中的数据节点
typedef struct Node
{
	int iData;
	struct Node *pNext;
}Node;

//链表的头
typedef struct List
{
	int iLen;
	Node *pFirstNode;   //用来保存第一个数据节点的地址
}List;

//产生数据节点
Node *mkNode()
{
	Node *node = (Node*)malloc(sizeof(Node));
	if (NULL == node)
	{
		printf("malloc node failed...\n");
		exit(EXIT_FAILURE);
	}
	memset(node, 0, sizeof(Node));
	return node;
}

//产生链表的头
List *mkList()
{
	List *list = (List *)malloc(sizeof(List));
	if (NULL == list)
	{
		printf("mallco list failed...\n");
		exit(EXIT_FAILURE);
	}
	memset(list, 0, sizeof(List));
	return list;
}

void insert(List *list, Node *node)
{
	if (NULL == list || NULL == node)
	{
		return;
	}

	node->pNext = list->pFirstNode;
	list->pFirstNode = node;
	list->iLen++;
}

void display(const List *list)
{
	if (NULL == list)
	{
		return;
	}
	Node *node = list->pFirstNode;
	while (NULL != node)
	{
		printf("%d ", node->iData);
		node = node->pNext;
	}
	printf("\n");
}

void bubble(List *list)
{
	if (NULL == list)
	{
		return;
	}

	Node *pre = NULL;
	Node *cur = NULL;
	int i = 0;
	int j = 0;
	for (; i<list->iLen; i++)
	{
		pre = list->pFirstNode;
		cur = pre;	
		for (j=0; j<list->iLen-1; j++)
		{
			if (cur->iData > cur->pNext->iData)	
			{
				if (cur == list->pFirstNode)
				{
					list->pFirstNode = cur->pNext;
					cur->pNext = cur->pNext->pNext;
					list->pFirstNode->pNext = cur;
					pre = list->pFirstNode;
					continue;
				}
				else
				{
					pre->pNext = cur->pNext;
					cur->pNext = cur->pNext->pNext;
					pre->pNext->pNext = cur;
					pre = pre->pNext;
					continue;
				}
			}
			else
			{
				pre = cur;
				cur = cur->pNext;
			}
		}
	}
}

int main(int argc, char *argv[])
{
	List *list = mkList();
	int i = 0;
	Node *node = NULL;
	for (; i<5; i++)
	{
		node = mkNode();
		printf("请输入节点数据:\n");
		scanf("%d", &node->iData);
		insert(list, node);
	}
	display(list);

	bubble(list);
	printf("----------------\n");
	display(list);

	FILE *file = fopen(argv[1], "w");
	if (NULL == file)
	{
		printf("open %s failed -> %s\n", argv[1], strerror(errno));
		exit(EXIT_FAILURE);
	}

	node = list->pFirstNode;
	while (NULL != node)
	{
		fprintf(file, "%d\n", node->iData);
		node = node->pNext;
	}
	fclose(file);



	return 0;
}




